package com.lsh.ofc.core.service.impl;

import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.core.entity.OfcObdHead;
import com.lsh.ofc.core.entity.OfcOrderHead;
import com.lsh.ofc.core.entity.OfcSoHead;
import com.lsh.ofc.core.entity.OfcTask;
import com.lsh.ofc.core.enums.OfcTaskStatus;
import com.lsh.ofc.core.enums.OfcTaskType;
import com.lsh.ofc.core.enums.Valid;
import com.lsh.ofc.core.service.OfcOrderService;
import com.lsh.ofc.core.service.OfcSoService;
import com.lsh.ofc.core.service.OfcStoCreateService;
import com.lsh.ofc.core.service.OfcTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Project Name: lsh-ofc
 * Created by fuhao
 * Date: 18/6/19
 * Time: 18/6/19.
 * 北京链商电子商务有限公司
 * Package name:com.lsh.ofc.core.service.impl.
 * desc:类功能描述
 *
 * @author peter
 */
@Service
@Slf4j
public class OfcStoCreateServiceImpl implements OfcStoCreateService {

    @Autowired
    private OfcOrderService ofcOrderService;

    @Autowired
    private OfcSoService ofcSoService;

    @Autowired
    private OfcTaskService ofcTaskService;

    @Override
    @Transactional
    public int create(OfcOrderHead targetOrderHead, List<OfcSoHead> targetSoHeads) throws BusinessException {
        log.info("【sto 插入数据库订单信息】【开始】 orderCode = {}", targetOrderHead.getOrderCode());
        ofcOrderService.create(targetOrderHead, true);
        log.info("【sto 插入数据库订单信息】【结束】 orderCode = {}", targetOrderHead.getOrderCode());
        log.info("【sto 插入数据库SO单信息】【开始】");
        int so = ofcSoService.insert(targetSoHeads);
        log.info("【sto 插入数据库SO单信息】【结束】");

        return so;
    }

    @Override
    @Transactional
    public int createSoObd(OfcOrderHead targetOrderHead, OfcSoHead targetSoHead, OfcObdHead ofcObdHead) throws BusinessException {

        ofcOrderService.create(targetOrderHead, false);

        int so = ofcSoService.insert(targetSoHead);

        addPoTask(targetOrderHead);

        return so;
    }

    @Override
    @Transactional
    public boolean addPoTask(OfcOrderHead targetOrderHead) {

        try {
            int ts = (int) (System.currentTimeMillis() / 1000);
            OfcTask task = new OfcTask();
            task.setVenderId(targetOrderHead.getVenderId());
            task.setRefId(targetOrderHead.getOrderCode());
            task.setType(OfcTaskType.SO_PO_PSI.getValue());
            task.setStatus(OfcTaskStatus.NEW.getValue());
            task.setContent(targetOrderHead.getOrderCode() + "");
            task.setCreateTime(ts);
            task.setUpdateTime(ts);
            task.setValid(Valid.enable.getValue());
            task.setExecCount(0);

            this.ofcTaskService.addTask(task);
        } catch (Exception e) {
            log.error("添加SO_PO_PSI失败", e);
        }

        return true;
    }


}
